#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>

#define MAX_CITYS 1000
#define MAX_ROADS (3*MAX_CITYS)

typedef struct HEAP Heap;
typedef struct ROAD Road;
typedef Road ElementType;
struct ROAD{
	int start;
	int end;
	int price;
};

struct HEAP{
	ElementType *elm;
	int size;
	int capacity;
};
Heap *HeapInit(int capacity){
	Heap *h=malloc(sizeof(Heap));
	h->size=0;
	h->elm=malloc(sizeof(Heap)*(capacity+1));
	h->elm[0].price=INT_MIN;
	h->capacity=capacity;
	return h;
}
_Bool HeapEmpty(Heap *h){
	if( h->size == 0 )
		return true;
	return false;
}
_Bool HeapFull(Heap *h){
	if( h->capacity == h->size )
		return true;
	return false;
}
void InsertHeap(Heap *h,ElementType e){
	int i=++h->size;
	while( e.price < h->elm[i/2].price ){
		h->elm[i]=h->elm[i/2];
		i=i/2;
	}
	h->elm[i]=e;
	return;
}
ElementType DeleteHeap(Heap *h){
	ElementType ret=h->elm[1];
	ElementType e=h->elm[h->size--];
	int i=1;
	while( 2*i <= h->size ){
		if( 2*i != h->size && h->elm[2*i].price > h->elm[2*i+1].price \
		&& e.price > h->elm[2*i+1].price ){
			h->elm[i]=h->elm[2*i+1];
			i=2*i+1;
		}else if( h->elm[2*i].price < e.price ){
			h->elm[i]=h->elm[2*i];
			i=2*i;
		}else
			break;
	}
	h->elm[i]=e;
	return ret;
}
int Father(int index,int *set){
	int t;
	do{
		t=index;
		index=set[t];
	}while ( index > 0 );
	return t;
}
//_Bool CheckSet(int index1,int index2,int *set){
//	if( Father(index1,set) == Father(index2,set) )
//		return true;
//	return false;
//}
void Union(int f1,int f2,int *set){
	if( f1 == f2 )return;
	if( set[f1] <= set[f2] ){
		set[f1]+=set[f2];
		set[f2]=f1;
	}else if ( set[f1] > set[f2] ){
		set[f2]+=set[f1];
		set[f1]=f2;
	}
	return;
}

void PrtSet(int *set,int n){
	printf("\nSet\n");
	for(int i=1;i<=n;i++){
		printf("%3d",i);
	}
	printf("\n");
	for(int i=1;i<=n;i++){
		printf("%3d",set[i]);
	}
	printf("\n");
}

int main(void){
	int n,m,price=0;
	scanf("%d %d",&n,&m);
	int set[n+1];	// city index start from 1
	for(int i=0;i<=n;i++)set[i]=-1;
	Heap *h=HeapInit(MAX_ROADS);
	Road r;
	for(int i=0;i<m;i++){
		scanf("%d %d %d",&r.start,&r.end,&r.price);
		InsertHeap(h,r);
	}
	int f1,f2;
	while( !HeapEmpty(h) ){
		r=DeleteHeap(h);
//printf("%3d %3d %4d\n",r.start,r.end,r.price);
		f1=Father(r.start,set);
		f2=Father(r.end,set);
		if( f1 != f2 ){
			price+=r.price;
			Union(f1,f2,set);
		}
		//PrtSet(set,n);
	}
	int count=0;
	for(int i=1;i<=n;i++){
		if( set[i] < 0 )
			count++;
	}
	if( 1 == count )
		printf("%d",price);
	else
		printf("-1");
	return 0;
}
